import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Upload,
  Tag,
  DatePicker,
  Image,
  Popover,
  UploadFile,
  ConfigProvider
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  PlayCircleOutlined,
  SearchOutlined
} from '@ant-design/icons';
import { getDynamicPage, addDynamic, updateDynamic, deleteDynamic, DynamicInfo } from '@/services/DynamicService';
import { famousPersonId } from '@/services';
import styles from './index.less';
import dayjs from 'dayjs';
import { FileDetail } from '@/services/index';
import { uploadFile } from '@/services/FileService';
import zhCN from 'antd/locale/zh_CN';

const DynamicAdmin: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<DynamicInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [searchForm] = Form.useForm();
  const [currentImagePage, setCurrentImagePage] = useState(1);
  const [imageList, setImageList] = useState<UploadFile[]>([]);
  const [videoList, setVideoList] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const pageSize = 6; // 每页显示的图片数量
  const [videoModalVisible, setVideoModalVisible] = useState(false);
  const [currentVideo, setCurrentVideo] = useState('');
  const [videoRef, setVideoRef] = useState<HTMLVideoElement | null>(null);

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getDynamicPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
        type: values.type,
        status: values.status,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 添加表单重置函数
  const resetForm = () => {
    form.resetFields();
    setEditingId(undefined);
    setImageList([]);
    setVideoList([]);
  };

  // 修改 handleCancel
  const handleCancel = () => {
    setModalVisible(false);
    resetForm();
  };

    // 处理文件上传
    const handleFileUpload = async (options: any) => {
        const { file, onSuccess, onError } = options;
        try {
          const fileId = await uploadFile(file);
          onSuccess({
            uid: fileId,
            name: file.name,
            status: 'done',
            url: `/api/file/play/${fileId}`,
          });
        } catch (error) {
          onError(error);
          message.error('上传失败');
        }
      };

  // 修改表单提交处理
  const handleSubmit = async (values: any) => {
    try {
      // 获取成功上传的图片和视频ID
      const imageIds = imageList
        .filter(file => file.status === 'done')
        .map(file => file.response?.uid || file.uid)
        .join(',');

      const videoIds = videoList
        .filter(file => file.status === 'done')
        .map(file => file.response?.uid || file.uid)
        .join(',');

      const submitData = {
        ...values,
        famousPersonId,
        date: values.date ? dayjs(values.date).valueOf().toString() : undefined,
        imageIds,
        videoIds,
      };

      if (editingId) {
        await updateDynamic({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addDynamic(submitData);
        message.success('添加成功');
      }
      setModalVisible(false);
      resetForm();
      setImageList([]);
      setVideoList([]);
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 修改删除处理函数
  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条动态吗？删除后不可恢复。',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteDynamic([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理编辑
  const handleEdit = (record: DynamicInfo) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      date: record.date ? dayjs(record.date) : undefined,
    });

    // 设置图片列表
    if (record.imageList?.length) {
      setImageList(record.imageList.map(img => ({
        uid: String(img.id),
        name: img.fileName || `image-${img.id}`,
        status: 'done',
        url: `/api/file/play/${img.id}`,
      })));
    } else {
      setImageList([]);
    }

    // 设置视频列表
    if (record.videoList?.length) {
      setVideoList(record.videoList.map(video => ({
        uid: String(video.id),
        name: video.fileName || `video-${video.id}`,
        status: 'done',
        url: `/api/file/play/${video.id}`,
      })));
    } else {
      setVideoList([]);
    }

    setModalVisible(true);
  };

  // 处理搜索
  const handleSearch = () => {
    loadData(1);
  };

  // 处理重置
  const handleReset = () => {
    searchForm.resetFields();
    loadData(1, 20);
  };

    // 处理图片预览
  const handlePreview = async (file: UploadFile) => {
    const resp = file.response
    if (resp) {
      const fileId = resp.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    } else {
      const fileId = file.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    }
  };

  // 添加图片预览渲染函数
  const renderImagePreview = (imageList: FileDetail[]) => {
    if (!imageList || imageList.length === 0) return '-';
    
    const totalPages = Math.ceil(imageList.length / pageSize);

    const PopoverContent = () => {
      const startIndex = (currentImagePage - 1) * pageSize;
      const currentImages = imageList.slice(startIndex, startIndex + pageSize);

      return (
        <div className={styles.imageListContainer}>
          <div className={styles.imageList}>
            <Image.PreviewGroup>
              {currentImages.map((file) => (
                <div key={file.id} className={styles.imageItem}>
                  <Image
                    src={`/api/file/play/${file.id}`}
                    alt={file.fileName}
                    width={120}
                    height={120}
                    style={{ objectFit: 'cover', borderRadius: 4 }}
                    preview={{
                      mask: '预览',
                      maskClassName: styles.previewMask,
                    }}
                  />
                </div>
              ))}
            </Image.PreviewGroup>
          </div>
          {totalPages > 1 && (
            <div className={styles.pagination}>
              <Button
                size="small"
                disabled={currentImagePage === 1}
                onClick={() => setCurrentImagePage(prev => prev - 1)}
              >
                上一页
              </Button>
              <span className={styles.pageInfo}>
                {currentImagePage}/{totalPages}
              </span>
              <Button
                size="small"
                disabled={currentImagePage === totalPages}
                onClick={() => setCurrentImagePage(prev => prev + 1)}
              >
                下一页
              </Button>
            </div>
          )}
        </div>
      );
    };

    return (
      <div className={styles.imagePreview}>
        <Popover
          content={<PopoverContent />}
          title="图片列表"
          trigger="hover"
          placement="right"
          onOpenChange={(visible) => {
            if (visible) {
              setCurrentImagePage(1);
            }
          }}
        >
          <Tag color="processing" style={{ cursor: 'pointer' }}>
            {imageList.length} 张图片
          </Tag>
        </Popover>
      </div>
    );
  };

  // 添加视频预览处理函数
  const handleVideoPreview = (file: UploadFile) => {
    const videoUrl = file.response ? `/api/file/play/${file.response.uid}` : `/api/file/play/${file.uid}`;
    setCurrentVideo(videoUrl);
    setVideoModalVisible(true);
  };

  // 添加视频模态框关闭处理
  const handleModalClose = () => {
    setVideoModalVisible(false);
    if (videoRef) {
      videoRef.pause();
    }
  };

  // 添加处理视频播放的函数
  const handleVideoClick = (videoId: string) => {
    setCurrentVideo(`/api/file/play/${videoId}`);
    setVideoModalVisible(true);
  };

  // 处理表格变化
  const handleTableChange = (newPagination: any) => {
    loadData(newPagination.current, newPagination.pageSize);
  };

  // 添加渲染表单模态框函数
  const renderSearchForm = () => (
    <div className={styles.toolbarContent}>
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
      >
        <Form.Item name="keyword">
          <Input
            placeholder="请输入关键词"
            prefix={<SearchOutlined />}
            allowClear
            style={{ width: 250 }}
          />
        </Form.Item>
        <Form.Item name="type">
          <Select
            placeholder="类型"
            style={{ width: 120 }}
            allowClear
          >
            <Select.Option value={1}>普通动态</Select.Option>
            <Select.Option value={2}>置顶动态</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            placeholder="状态"
            style={{ width: 120 }}
            allowClear
          >
            <Select.Option value={0}>草稿</Select.Option>
            <Select.Option value={1}>已发布</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <Button type="primary" icon={<PlusOutlined />} onClick={() => {
        setEditingId(undefined);
        form.resetFields();
        setImageList([]);
        setVideoList([]);
        setModalVisible(true);
      }}>
        添加动态
      </Button>
    </div>
  );

  // 添加渲染模态框函数
  const renderModal = () => (
    <Modal
      title={editingId ? '编辑动态' : '新增动态'}
      open={modalVisible}
      onCancel={handleCancel}
      footer={null}
      width={800}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
      >
        <Form.Item
          name="title"
          label="标题"
          rules={[{ required: true, message: '请输入标题' }]}
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="content"
          label="内容"
          rules={[{ required: true, message: '请输入内容' }]}
        >
          <Input.TextArea rows={4} maxLength={500} showCount />
        </Form.Item>

        <Form.Item
          name="date"
          label="发布时间"
          rules={[{ required: true, message: '请选择发布时间' }]}
        >
          <DatePicker
            showTime={{ 
              format: 'HH:mm:ss',
              defaultValue: dayjs('00:00:00', 'HH:mm:ss')
            }}
            format="YYYY-MM-DD HH:mm:ss"
          />
        </Form.Item>

        <Form.Item label="图片">
          <Upload
            listType="picture-card"
            fileList={imageList}
            onChange={({ fileList }) => setImageList(fileList)}
            customRequest={handleFileUpload}
            multiple
            accept="image/*"
            maxCount={15}
            onRemove={(file) => {
              const newFileList = imageList.filter(item => item.uid !== file.uid);
              setImageList(newFileList);
              return true;
            }}
            onPreview={handlePreview}
          >
            {imageList.length >= 15 ? null : (
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传图片</div>
              </div>
            )}
          </Upload>
        </Form.Item>

        <Form.Item label="视频">
          <Upload
            fileList={videoList}
            onChange={({ fileList }) => setVideoList(fileList)}
            customRequest={handleFileUpload}
            multiple
            accept="video/*"
            maxCount={5}
            onPreview={handleVideoPreview}
            onRemove={(file) => {
              const newFileList = videoList.filter(item => item.uid !== file.uid);
              setVideoList(newFileList);
              return true;
            }}
          >
            {videoList.length >= 5 ? null : (
              <Button icon={<UploadOutlined />}>上传视频</Button>
            )}
          </Upload>
        </Form.Item>

        <Form.Item
          name="type"
          label="类型"
          rules={[{ required: true, message: '请选择类型' }]}
        >
          <Select>
            <Select.Option value={1}>普通动态</Select.Option>
            <Select.Option value={2}>置顶动态</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select>
            <Select.Option value={0}>草稿</Select.Option>
            <Select.Option value={1}>发布</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item className={styles.modalFooter}>
          <Space>
            <Button onClick={handleCancel}>取消</Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      width: '25%',
      ellipsis: true,
    },
    {
      title: '发布时间',
      dataIndex: 'date',
      key: 'date',
      width: '12%',
      valueType: 'dateTime',
      sorter: true,
      render: (_, record) => dayjs(parseInt(record.date)).format('YYYY-MM-DD HH:mm:ss'),
      renderFormItem: () => (
        <DatePicker 
          showTime={{ 
            format: 'HH:mm:ss',
            defaultValue: dayjs('00:00:00', 'HH:mm:ss')
          }}
          format="YYYY-MM-DD HH:mm:ss"
        />
      ),
    },
    {
      title: '图片',
      dataIndex: 'imageList',
      key: 'imageList',
      width: '10%',
      render: (imageList: FileDetail[]) => renderImagePreview(imageList),
    },
    {
      title: '视频',
      dataIndex: 'videoList',
      key: 'videoList',
      width: '10%',
      render: (videoList: FileDetail[]) => {
        if (!videoList?.length) return '-';
        
        const content = (
          <div className={styles.videoPopoverList}>
            {videoList.map((video) => (
              <div 
                key={video.id} 
                className={styles.videoItem}
                onClick={() => handleVideoClick(String(video.id))}
              >
                <PlayCircleOutlined />
                <span>{video.fileName || `未命名视频`}</span>
              </div>
            ))}
          </div>
        );

        return (
          <Popover 
            content={content}
            title="视频列表"
            trigger="hover"
            placement="right"
          >
            <Tag color="processing" className={styles.videoTag}>
              <PlayCircleOutlined /> {videoList.length} 个视频
            </Tag>
          </Popover>
        );
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '8%',
      render: (type: number) => (
        <Tag color={type === 2 ? 'red' : 'blue'}>
          {type === 2 ? '置顶动态' : '普通动态'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '8%',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'orange'}>
          {status === 1 ? '已发布' : '草稿'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '12%',
      render: (_: any, record: DynamicInfo) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <ConfigProvider locale={zhCN}>
      <Card title="动态管理">
        <div className={styles.toolbar}>
          {renderSearchForm()}
        </div>
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          scroll={{ y: 'calc(100vh - 410px)', scrollToFirstRowOnChange: false }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['20', '50', '100'],
          }}
          onChange={handleTableChange}
        />
        {renderModal()}
        {/* 添加视频播放模态框 */}
        <Modal
          title="视频播放"
          open={videoModalVisible}
          onCancel={handleModalClose}
          footer={null}
          width={800}
          centered
          destroyOnClose
        >
          <video
            ref={(ref) => setVideoRef(ref)}
            src={currentVideo}
            controls
            style={{ width: '100%' }}
            autoPlay
          />
        </Modal>

        {/* 添加预览组件 */}
        {previewImage && (
          <Image
            style={{ display: 'none' }}
            preview={{
              visible: previewOpen,
              src: previewImage,
              onVisibleChange: (visible) => {
                setPreviewOpen(visible);
                if (!visible) {
                  setPreviewImage('');
                }
              },
              fallback: ''
            }}
          />
        )}
      </Card>
    </ConfigProvider>
  );
};

export default DynamicAdmin; 